package class202205.demo31.demo26;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class ReflectClassDemo {
    public static void reflectNewInstance()  {
        try {
            Class<?> c1 = Class.forName("reflectdome1.Student");
            Constructor<?> constructor = c1.getDeclaredConstructor(String.class,int.class);

            constructor.setAccessible(true);

            Student student = (Student) constructor.newInstance("a wei",18);
            System.out.println();

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

    }

    /**
     *反射属性  获取私有  或公开
     */

    public static void reflectPrivateField(){
        try {
            Class<?> c1 = Class.forName("Student");
            Student student = (Student) c1.newInstance();
            Field field = c1.getDeclaredField("name");
            //所有私有的都要调用setAccessible置为true
            field.setAccessible(true);

            //设置那个对象
            field.set(student,"laoli");
            System.out.println(student);

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        reflectPrivateField();
    }

}
